/**
 * Copyright (c) 2006-2012 Las Venturas Playground, LVP Mineground
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package mineground.bukkit;

import java.util.HashMap;

import mineground.core.Message;
import mineground.core.MessageLoop;
import mineground.core.MessageLoopThread;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;

/**
 * 
 * 
 * 
 * 
 */
public class EventListener implements Listener {
    /**
     * 
     * 
     */
    private MessageLoop mMessageLoop;
    
    /**
     * 
     * 
     */
    private HashMap<Player, NativePlayer> mPlayerMap = new HashMap<Player, NativePlayer>();
    
    /**
     * 
     * 
     */
    private EventListener(MessageLoop messageLoop) {
        mMessageLoop = messageLoop;
    }
    
    /**
     * 
     * 
     */
    @EventHandler
    public void onPlayerLogin(PlayerLoginEvent event) {
        NativePlayer nativePlayer = new NativePlayer(event.getPlayer());
        mPlayerMap.put(event.getPlayer(), nativePlayer);
        
        mMessageLoop.postMessage(MessageLoopThread.GameThread, Message.PlayerJoinEvent,
            nativePlayer);
    }
    
    /**
     * 
     * 
     */
    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        mMessageLoop.postMessage(MessageLoopThread.GameThread, Message.PlayerQuitEvent,
            mPlayerMap.get(event.getPlayer()), event.getQuitMessage());
    }
    
    /**
     * 
     * 
     */
    @EventHandler
    public void onPlayerChat(PlayerChatEvent event) {
        mMessageLoop.postMessage(MessageLoopThread.GameThread, Message.PlayerChatEvent,
            mPlayerMap.get(event.getPlayer()), event.getMessage());
        event.setCancelled(true);
    }
    
    /**
     * 
     * 
     */
    public static void create(JavaPlugin bukkit, MessageLoop messageLoop) {
        bukkit.getServer().getPluginManager().registerEvents(
            new EventListener(messageLoop), bukkit);
    }
}
